<?PHP
session_start();
include("common/connect.php");
include("common/common.php");

if( !isset($_SESSION["user"]) ) 
{
	$url = "Location:login.php?ref=deal_mall_trade.php";
	header($url);
}

$id = CheckUrlParamNoDie("id");
$opt = CheckUrlParamNoDie("opt");
$tbid = CheckUrlParamNoDie("tbid");
$opter = CheckUrlParamNoDie("opter");
$tradeid = CheckUrlParamNoDie("tradeid");
if (trim($tradeid)=="" || $tbid=="")
{
	echo "<script>alert('严重错误！订单号不能为空，请立即找冰峰！');</script>";
	exit;
}
$phone = "";
$userid="";
$info = "";
$userid="";

//echo $opt;
if ($opt == "giveup")
{
	mysql_query( "update duoduo_mall_order set handle_code=0,operater='' where u_id='$tbid'");
	if (mysql_affected_rows() == 0)
		echo "<script>alert('error, please notify me.');</script>";
	else
		echo "<script>window.history.go(-2);</script>";

	exit;
}

if (strlen($tbid) < 6)	// id
{
	$result = mysql_query( "select tb_id from user where id=$tbid limit 1" );
    if (mysql_num_rows($result) > 0)
    {
		$userid = $tbid;
		$row = mysql_fetch_assoc( $result );
		$tbid = $row["tb_id"];
	}
}

//
if ($opt == "getphone")
	$tbid = trim(GetPostParamStr("tb"));

// 取Phone和userid
if ($tbid)
{
	$result = mysql_query( "select id,phone from user where tb_id='" .$tbid. "' limit 1" );
    if ($result)
    {
		$row = mysql_fetch_assoc( $result );
		$phone = $row["phone"];
		$userid = $row["id"];
	}
}
	
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
<!--
body,td,th {
	font-family: 宋体;
	font-size: 13px;
	color: #000;
}
body {
	background-color: #FFF;
}
-->
</style>

<script language="javascript" src="js/common.js"></script>
<script language="javascript">
function OnBtn(strAction)
{
	var tbid = document.getElementById("tb_id").value;
	var phone = document.getElementById("phone_id").value;
	
	if( tbid == "" || ((!isemail( tbid )) && (!isphone( tbid ))) )
	{
		alert( "用户支付宝帐号输入有误！" );
		document.getElementById("tb_id").focus();
		return;
	}
	
	document.getElementById("form1").action = strAction + "&id=<?PHP echo $id; ?>&tbid=<?PHP echo $tbid; ?>&tradeid=<?PHP echo $tradeid; ?>";
	document.getElementById("form1").submit();
}
</script>

<?php

//echo $t[1];
//exit;

if ($opt == "")
{
	$sql = "update duoduo_mall_order set handle_code = 1,operater='".$_SESSION["user"]."' where handle_code = 0 and (stat_desc ='核对有效' or tiqian = 1) and (id=$id or u_id='$userid')";	
	$result = mysql_query( $sql );
	if (mysql_affected_rows() == 0)
	{
		echo "<script>alert('已经有人在处理了哦，呵呵');window.history.back();</script>";
		//exit;
	}
}
else if ($opt == "savein" || $opt == "savein_ok")
{
	$bInOK = 0;
	if ($opt == "savein_ok")
		$bInOK = 1;

	$tbid = trim(GetPostParamStr("tb"));
	$phone = trim(GetPostParamStr("phone"));
	$info = trim(GetPostParamStr("info"));

	$allCommission = 0;
	$srcIds = explode(',', GetPostParamStr("srcIds"));
	for($i=0; $i < count($srcIds) - 1; $i++)
	{
		$allCommission += _DealItemSrc(2, $srcIds[$i], $userid, $tbid, $phone, $info);
	
		// 更新源表
		$sql = "update duoduo_mall_order set handle_code = 2,operater='".$_SESSION["user"]."' where id=".$srcIds[$i]." and handle_code = 1 limit 1";
		echo $sql."<br>";
		$result = mysql_query( $sql );
		if (mysql_affected_rows() == 0)
		{
			echo "<script>alert('更新源表状态到2时出错！');window.history.back();</script>";
			exit;
		}
	}

	//
	$desIds = explode(',', GetPostParamStr("desIds"));
	for($i=0; $i < count($desIds) - 1; $i++)
	{
		_DealItemDes($bInOK, $desIds[$i], $tbid, $phone, $info);
	}

	// 消息
	mysql_query( "insert into gwt_msg (touser,content) values ($userid, '您在购物兔成功购物获得返现，本次赠送您 ".round($allCommission*10, 0)." 兔币。')" );

	echo "<script>alert('处理成功！');window.history.go(-2);</script>";
	exit;
}

function _DealItemSrc( $bInOK, $id, $userid, $tbid, $phone, $info)
{
	$result = mysql_query( "select * from duoduo_mall_order where id=" . $id . " and handle_code = 1 limit 1" );
    if ($result)
    {
		$row = mysql_fetch_assoc( $result );
		$sql = "insert into order_handle_report (user_id,
		app_key, outer_code, trade_id, pay_time, pay_price,real_pay_fee,item_title, item_num, shop_title, 
		commission_rate, commission, num_iid, seller_nick, 
		phone, tbid, info, 
		handle_code, operater, a_no) 
		values ($userid,
		'','','".GetTradeId($row)."','".$row["order_time"]."',
		'".$row["sales"]."','".$row["sales"]."','','".$row["item_count"]."','',
		'0','".$row["commission"]."','','".$row["merchant_id"]."',
		'".$phone."','".$tbid."','".$info."',".$bInOK.",'".$_SESSION["user"]."',100)";
		echo $sql."<br>";
		$result2 = mysql_query( $sql );
		if (mysql_affected_rows() == 0)
		{
			echo "<script>alert('处理过程中发生失败，请告诉程序员，出错代码：1');window.history.back();</script>";
			exit;
		}
		
//		return $row["fxje"];
		
		// 操作日志
		mysql_query( "insert into opt_log (`sql`) values ('".mysql_real_escape_string($sql)."')" );
		
		// 加兔币
		$addlevel = $row["fxje"]*10;	// x/10*100
		mysql_query( "update user set level=level+$addlevel,tubi=tubi+$addlevel where id=$userid" );
		$_res = mysql_query( "select commend_id,all_fx from user where id=$userid" );
		$_row = mysql_fetch_assoc( $_res );
		if ($_row["commend_id"] != "" && is_numeric($_row["commend_id"]) && $_row["all_fx"] == 0)	// 有上线用户并且是第一次购物
		{
			mysql_query( "update user set level=level+100,tubi=tubi+100 where id=".$_row["commend_id"] );
			mysql_query( "insert into gwt_msg (touser,content) values (".$_row["commend_id"].",'您邀请的好友（".substr($tbid, 0, 5)."***）在购物兔成功购物啦，现赠送您 100 兔币，再接再厉哦。')" );
		}
		
		// 一共返了多少
		mysql_query( "update user set all_fx=all_fx+".round($row["fxje"], 2)." where id=$userid" );
		
		return $row["fxje"];
    }
	else
	{
		echo "<script>alert('处理过程中发生失败，请告诉程序员，出错代码：2');window.history.back();</script>";
		exit;
	}
	
	return 0;
}

function _DealItemDes( $bInOK, $id, $tbid, $phone, $info)
{
	$result = mysql_query( "select * from duoduo_mall_order where id=" . $id . " limit 1" );
    if ($result)
    {
		$row = mysql_fetch_assoc( $result );
		$tubi = $row["fxje"] * 100;
		if ($row["stat_desc"] == "核对有效")
		{
			$sql = "update duoduo_mall_order set tiqian=2 where id=".$id;
			echo $sql."<br>";
			mysql_query( $sql );
			
			// 
			$sql = "update user set tubi=tubi+$tubi where id=".$row["u_id"];
			echo $sql."<br>";
			mysql_query( $sql );
			mysql_query( "insert into gwt_msg (touser,content) values ($userid,'您之前由于申请提前返现被冻结的 $tubi 个兔币已解冻回您的账号中，祝购物愉快！')" );
		}	
		else if (IsBadOrder($row["stat_desc"]))
		{
			;	// 不用管，兔币在提前申请时已经扣了，这个单会一直显示在用户返现列表中，以示警惕
		}
	}
}
?>
</head>

<body>
<br />

<table cellpadding="0" cellspacing="0" border="1" align="center">
	<tr>
    	<td height="25" width="50" align="center">序列号</td>
        <td width="200" align="center">时间</td>
        <td width="158" align="center">支付宝帐号</td>
      	<td width="298" align="center">订单号</td>
        <td width="198" align="center">商城</td>
        <td width="70" 	align="center">交易额</td>
        <td width="144" align="center">佣金额</td>
        <td width="144" align="center">本次需返金额</td>
        <td width="143" align="center">订单状态</td>
        <td width="143" align="center">操作员</td>
        <td width="143" align="center">说明</td>
    </tr>
<tr><td colspan="7" align="center">--------本次需返现的单号------------</td></tr>
<?PHP

$fNeedBackMoney = 0.0;
$srcIds = "";		// 源表的Id
$desIds = "";		// 目标表的Id
$strTradeIds = "购物兔返款，如果是促销产品，实际返现会稍少一些，本次返款订单列表如下：";	// 本次交易订单号列表
$sql = "select * from duoduo_mall_order where handle_code = 1 and (stat_desc ='核对有效' or tiqian = 1) and (id =$id or u_id='$userid') order by id desc";
//echo $sql;
//exit;
$result = mysql_query( $sql );
while( $result && $row = mysql_fetch_assoc( $result ))
{
	$itemFX = $row["fxje"];				// 返现金额是已经*0.6的
	$fNeedBackMoney += $itemFX;
	$srcIds .= $row["id"] . ",";
	$strTradeIds .= $row["merchant_id"].":".$row["order_code"].", ￥$itemFX; ";
?>
<tr>
    <td height="25" width="50" align="center"><?PHP echo $row["id"]; ?></td>
    <td width="200" align="center" title="<?PHP echo "操作时间：".$row["opt_time"]; ?>"><?PHP echo $row["order_time"]; ?></td>
	<td width="198" align="center" title="<?PHP echo $userid; ?>"><?PHP echo $tbid; ?>&nbsp;</td>
	<td width="70" 	align="center" title="<?PHP echo $row["item_count"]."件"; ?>"><?PHP echo GetTradeId($row); ?>&nbsp;</td>
    <td width="70" 	align="center"><?PHP echo $row["merchant_id"]; ?>&nbsp;</td>
	<td width="144" align="center"><?PHP echo $row["sales"]; ?>&nbsp;</td>
	<td width="158" align="center"><?PHP echo $row["commission"]; ?>&nbsp;</td>
    <td width="158" align="center"><?PHP echo $itemFX; ?>&nbsp;</td>
    <td width="143" align="center"><?PHP echo $row["stat_desc"]; ?></td>
	<td width="143" align="center"><?PHP echo $row["operater"]; ?></td>
    <td width="143" align="center">&nbsp;</td>
</tr>
<?PHP
}
?>

<tr>
  <td colspan="7" align="center">-------提前返现，现在已有结果的-------------</td>
</tr>
<?PHP
function IsBadOrder($stat_desc)
{
	return ($stat_desc=='核对无效' || $stat_desc=='申请取消' || $stat_desc=='申清取消');
}

// 提前返现，现已经有结果
$sql = "select * from duoduo_mall_order where handle_code = 2 and tiqian = 1 and u_id='$userid' and stat_desc<>'未核对' order by id desc";
$result = mysql_query( $sql );
while( $result && $row = mysql_fetch_assoc( $result ))
{
//	$fNeedBackMoney += $needFx;	
	$desIds .= $row["id"] . ",";
//	$strTradeIds .= $row["trade_id"].", ￥$needFx; ";
?>
<tr <?PHP if (IsBadOrder($stat_desc)) echo 'bgcolor="#CC0000"'; ?>>
    <td height="25" width="50" align="center"><?PHP echo $row["id"]; ?></td>
    <td width="200" align="center" title="<?PHP echo "操作时间：".$row["opt_time"]; ?>"><?PHP echo $row["order_time"]; ?></td>
	<td width="198" align="center" title="<?PHP echo $userid; ?>"><?PHP echo $tbid; ?>&nbsp;</td>
	<td width="70" 	align="center" title="<?PHP echo $row["item_count"]."件"; ?>"><?PHP echo GetTradeId($row); ?>&nbsp;</td>
    <td width="70" 	align="center"><?PHP echo $row["merchant_id"]; ?>&nbsp;</td>
	<td width="144" align="center"><?PHP echo $row["sales"]; ?>&nbsp;</td>
	<td width="158" align="center"><?PHP echo $row["commission"]; ?>&nbsp;</td>
    <td width="158" align="center">N/A&nbsp;</td>
    <td width="143" align="center"><?PHP echo $row["stat_desc"]; ?></td>
	<td width="143" align="center"><?PHP echo $row["operater"]; ?></td>
    <td width="143" align="center">&nbsp;</td>
</tr>
<?PHP
}
?>

<tr><td colspan="7" align="center">-------提前返现，还未有结果的-------------</td></tr>
<?PHP
// 之前未返现的
$sql = "select * from duoduo_mall_order where tiqian = 1 and u_id='$userid' and stat_desc='未核对' order by id desc";
$result = mysql_query( $sql );
while( $result && $row = mysql_fetch_assoc( $result ))
{
?>
<tr>
    <td height="25" width="50" align="center"><?PHP echo $row["id"]; ?></td>
    <td width="200" align="center" title="<?PHP echo "操作时间：".$row["opt_time"]; ?>"><?PHP echo $row["order_time"]; ?></td>
	<td width="198" align="center" title="<?PHP echo $userid; ?>"><?PHP echo $tbid; ?>&nbsp;</td>
	<td width="70" 	align="center" title="<?PHP echo $row["item_count"]."件"; ?>"><?PHP echo GetTradeId($row); ?>&nbsp;</td>
    <td width="70" 	align="center"><?PHP echo $row["merchant_id"]; ?>&nbsp;</td>
	<td width="144" align="center"><?PHP echo $row["sales"]; ?>&nbsp;</td>
	<td width="158" align="center"><?PHP echo $row["commission"]; ?>&nbsp;</td>
    <td width="158" align="center"><?PHP echo $row["fxje"]; ?>&nbsp;</td>
    <td width="143" align="center"><?PHP echo $row["stat_desc"]; ?></td>
	<td width="143" align="center"><?PHP echo $row["operater"]; ?></td>
    <td width="143" align="center">&nbsp;</td>
</tr>
<?PHP
}
?>

</table>

<hr />
<form method="post" id="form1" name="form1" >
<table cellpadding="0" cellspacing="0" border="1" align="center">
    <tr>
   	  <td width="60" height="30" align="center">账号：</td>
      <td width="140" height="22"><input type="text" width="140" id="tb_id" name="tb" height="20" value="<?PHP echo $tbid; ?>" onclick="javascript:select();" /></td>
      <td height="30"> 手机号： 
        <input type="text" width="140" id="phone_id" name="phone" height="20" value="<?PHP echo $phone; ?>" onclick="javascript:select();" /><input type="button" name="btnin" value="更新数据" onclick="javascript:OnBtn('?opt=getphone');" <?PHP if ($tbid != "") echo "disabled='disabled'"; ?> />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <?PHP 
		$hasReturn = mysql_result(mysql_query("select sum(commission)*0.6 as tmp from order_handle_report where handle_code=1 and tbid='".$tbid."'"), 0, "tmp");
//		$fNeedBackMoney = round($fNeedBackMoney * 0.6, 2);				// 百家商城前面已经从fxje取的
		$bNeedExt1Yuan = $hasReturn ==0.0 && $fNeedBackMoney < 1.0;
		if ($bNeedExt1Yuan)		// 第一次返现而且总额少于1元
		{
			if (mb_strlen($strTradeIds,'utf8') > 170)
			{
				$strTradeIds = mb_substr($strTradeIds,0,170,'UTF-8');
				$strTradeIds = strrev($strTradeIds);
				$strTradeIds = substr($strTradeIds, strpos($strTradeIds, ";"));
				$strTradeIds = strrev($strTradeIds);
				$strTradeIds .= " 等，第一次购物额外赠送1元，详情请参见个人中心。"; 
			}
			else
				$strTradeIds .= "第一次购物额外赠送1元，详情请参见个人中心。"; 
				
			$fNeedBackMoney += 1.0;
		}
		else
		{
			if (mb_strlen($strTradeIds,'utf8') > 185)
			{
				$strTradeIds = mb_substr($strTradeIds,0,185,'UTF-8');
				$strTradeIds = strrev($strTradeIds);
				$strTradeIds = substr($strTradeIds, strpos($strTradeIds, ";"));
				$strTradeIds = strrev($strTradeIds);
				$strTradeIds .= " 等，详情请参见个人中心。"; 
			}
			else
				$strTradeIds .= "详情请参见个人中心。"; 		
		}
			
		$_data = ($tbid."|".$phone."|".$fNeedBackMoney."|购物兔返款，欢迎推荐给好友~|".$strTradeIds); 
//		$_data = ($tbid."|".$phone."|".$fNeedBackMoney."|购物兔返款，返利狂欢，礼物多多，欢迎关注|".$strTradeIds); 
		?>
        
<a href="http://_my_data_transport_/?<?PHP echo $_data; ?>" target="_blank">去返款</a>
        </td>
    </tr>
    <tr>
    	<td colspan="2" height="30" align="right">共需返还金额：</td>
        <td><input type="text"  width="340" id="all_return_id" name="all_return" height="20" value="<?PHP echo $fNeedBackMoney; ?>" />&nbsp;</td>
    </tr>
    <tr>
    	<td colspan="2" height="30" align="right"s>备注：</td>
        <td><textarea name="info" cols="56" rows="7"><?PHP echo $info; ?></textarea></td>
    </tr>
    <tr>
    	<td colspan="3" height="30" align="center">
        <input type="hidden" name="srcIds" value="<?PHP echo $srcIds; ?>" />
        <input type="hidden" name="desIds" value="<?PHP echo $desIds; ?>" />
        <input type="button" name="btnin_ok" value="入库并标志返现" onclick="javascript:OnBtn('?opt=savein_ok');"/>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <a href="?opt=giveup&tradeid=<?PHP echo $tradeid; ?>&tbid=<?PHP echo $userid; ?>">放弃处理</a>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        </td>
    </tr>
</table>
</form>

<div align="center">
<input type="text" width="180" height="20" value="购物兔返款，欢迎推荐给好友" onclick="javascript:select();" />
<input type="text" width="180" height="20" value="<?PHP echo $strTradeIds; ?>" onclick="javascript:select();" />
<?PHP
echo "此用户共返了 ".$hasReturn."元";
?>

</div>

</body>
</html>